package com.zy.chat.chatai;


import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
public class ChatAi    {


    public void chatWithAI(ChannelHandlerContext ctx,TextWebSocketFrame msg) throws IOException {
        JSONObject jsonObject  = JSONObject.parseObject(msg.text());
        String username=jsonObject.getString("username");
        String touser=jsonObject.getString("touser");
        String content=jsonObject.getString("content").replace("\n","");
        String type=jsonObject.getString("type");
        String chattype=jsonObject.getString("chattype");

        ChatGptClient chatGptClient= new ChatGptClient();

        String prompt = content;
        String completion = chatGptClient.getCompletion(prompt);



        JSONObject back = new JSONObject();
        back.put("fromuser", username);
        back.put("content", completion);
        back.put("type",type);
        back.put("chattype",chattype);
        sendMessage(ctx,back.toJSONString());
    }


    private void sendMessage(ChannelHandlerContext ctx, String responseJson) {
        System.out.println("服务器发回消息"+responseJson);
        ctx.channel().writeAndFlush(new TextWebSocketFrame(responseJson));
    }

}
